package com.wps.wdztv6.api.operate;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.wps.wdztv6.api.common.Constants;
import com.wps.wdztv6.api.request.*;
import com.wps.wdztv6.api.response.*;
import com.wps.wdztv6.common.HttpPostUtil;
import com.wps.wdztv6.utils.WPS4Util;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Log4j2
public class WdztOperateApi {
    public static final String CONTENT_TYPE = "application/json";

    public static final String[] FILE_TYPES = {"w","s","p","f"};

    public static FormatConvertResponse convertFile(String host, String taskId, String docUrl,
                                                    String docFilename, String target) throws Exception {
        String url = "/api/cps/sync/v1/convert";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("task_id",taskId);
        jsonObject.put("doc_url",docUrl);
        jsonObject.put("doc_filename",docFilename);
        jsonObject.put("target_file_format",target);
        String content = jsonObject.toJSONString();
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,FormatConvertResponse.class);
    }

    /**
     * 多书签套用
     * @param host 中台入口地址
     * @param templateUrl 样板文件地址
     * @param templateFilename 样板文件名
     * @param sampleList 书签列表
     */
    public static WrapHeaderResponse wrapHeader(String host,String taskId,String templateUrl,String templateFilename,
                                                List<WrapHeaderRequest.Sample> sampleList) throws Exception {
        String url = "/api/cps/sync/v1/wrapheader";
        WrapHeaderRequest requestBody = WrapHeaderRequest.builder()
                .taskId(taskId)
                .templateUrl(templateUrl)
                .templateFilename(templateFilename)
                .sampleList(sampleList)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,WrapHeaderResponse.class);
    }

    /**
     * 清稿
     * @param docUrl 文档地址
     * @param docFilename 文档名称
     * @return 文档处理结果
     */
    public static OperateContentResponse contentOperateClean(String host,String taskId, String docUrl, String docFilename) throws Exception {
        // 清稿参数
        ArrayList<String> cleanOptions = new ArrayList<>();
        cleanOptions.add(Constants.ContentOperateCleanOptions.ACCEPT_ALL_REVISIONS);
        cleanOptions.add(Constants.ContentOperateCleanOptions.DELETE_ALL_COMMENTS);
        cleanOptions.add(Constants.ContentOperateCleanOptions.DELETE_ALL_INK);
        OperateContentRequest.Step.Args args = OperateContentRequest.Step.Args.builder()
                .cleanOptions(cleanOptions)
                .build();
        // 清稿步骤
        OperateContentRequest.Step step = OperateContentRequest.Step.builder()
                .operate(Constants.ContentOperateStepTypes.OFFICE_CLEAN)
                .args(args)
                .build();
        ArrayList<OperateContentRequest.Step> steps = new ArrayList<>();
        steps.add(step);
        return contentOperate(host,taskId,docUrl,docFilename,steps);
    }

    /**
     * 添加水印
     * @param docUrl 文档地址
     * @param docFilename 文档名称
     * @return 文档处理结果
     */
    public static OperateContentResponse contentOperateWatermark(String host,String taskId,String docUrl,String docFilename,
                                                                 String waterImgUrl,String waterImgName) throws Exception {
        // 文字水印
        OperateContentRequest.Step.Args.TextWatermark textWatermark = OperateContentRequest.Step.Args.TextWatermark.builder()
                .content("禁止预览，您已被监控")
                .tiled(true)
                .size(20)
                .transparent(0.5f)
                .position(Constants.WatermarkPosition.CENTER)
                .color("#CC00FF")
                .build();
        // 图片水印
        OperateContentRequest.Step.Args.ImageWatermark imageWatermark = OperateContentRequest.Step.Args.ImageWatermark.builder()
                .watermarkFilename(waterImgName)
                .watermarkUrl(waterImgUrl)
                .position(Constants.WatermarkPosition.CENTER)
                .tiled(true)
                .scale(1f)
                .tilt(true)
                .transparent(0.5f)
                .build();
        // 水印参数
        OperateContentRequest.Step.Args args = OperateContentRequest.Step.Args.builder()
                .textWatermark(textWatermark)
                .imageWatermark(imageWatermark)
                .build();
        // 水印步骤
        OperateContentRequest.Step step = OperateContentRequest.Step.builder()
                .operate(Constants.ContentOperateStepTypes.OFFICE_WATERMARK)
                .args(args)
                .build();
        // 步骤集合
        ArrayList<OperateContentRequest.Step> steps = new ArrayList<>();
        steps.add(step);
        return contentOperate(host,taskId,docUrl,docFilename,steps);
    }

    private static OperateContentResponse contentOperate(String host,String taskId, String docUrl, String docFilename,
                                                         ArrayList<OperateContentRequest.Step> steps) throws Exception {
        String url = "/api/cps/sync/v1/content/operate";
        OperateContentRequest requestBody = OperateContentRequest.builder()
                .taskId(taskId)
                .docUrl(docUrl)
                .docFilename(docFilename)
                .steps(steps)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,OperateContentResponse.class);
    }

    /**
     * 文档合并
     * @param docUrl1 文档1
     * @param docFilename1 文档1名字
     * @param docUrl2 文档2
     * @param docFilename2 文档2名字
     * @return 文档处理结果
     * @throws Exception
     */
    public static DocumentMergeResponse mergeFile(String host,String taskId, String docUrl1, String docFilename1,
                                                  String docUrl2, String docFilename2) throws Exception {
        String url = "/api/cps/sync/v1/merge";
        MergeDocumentRequest.MergeFile mergeFile1 = MergeDocumentRequest.MergeFile.builder()
                .docUrl(docUrl1)
                .docFilename(docFilename1)
                .build();
        MergeDocumentRequest.MergeFile mergeFile2 = MergeDocumentRequest.MergeFile.builder()
                .docUrl(docUrl2)
                .docFilename(docFilename2)
                .build();

        ArrayList<MergeDocumentRequest.MergeFile> mergeFileArrayList = new ArrayList<>();
        mergeFileArrayList.add(mergeFile1);
        mergeFileArrayList.add(mergeFile2);

        MergeDocumentRequest requestBody = MergeDocumentRequest.builder()
                .taskId(taskId)
                .mergedFileList(mergeFileArrayList).build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,DocumentMergeResponse.class);
    }


    /**
     * 平均拆分文档
     * @param docUrl 文档地址
     * @param docFilename 文档名称
     * @param averageSize 平均文档拆分大小
     * @param start 平均文档拆分开始
     * @param end 平均文档拆分结束
     * @return 文档拆分结果
     * @throws Exception
     */
    public static DocumentSplitResponse splitFileByAverage(String host,String taskId, String docUrl, String docFilename,
                                                           int averageSize, Integer start, Integer end) throws Exception {
        // 拆分文档范围
        DocumentSplitRequest.Average.SplitRange splitRange = DocumentSplitRequest.Average.SplitRange.builder()
                .start(start)
                .end(end)
                .build();
        DocumentSplitRequest.Average average = DocumentSplitRequest.Average.builder()
                .size(averageSize)
                .splitRange(splitRange)
                .build();
        return splitFile(host,taskId,docUrl,docFilename,Constants.DocumentSplitType.AVERAGE,average,null);
    }

    /**
     * 文档拆分
     * @param docUrl 文档地址
     * @param docFilename 文档名称
     * @param ranges 制定拆分范围 比如 1-2 ，2-3
     * @return 制定范围拆分文档结果
     * @throws Exception
     */
    public static DocumentSplitResponse splitFileByRanges(String host,String taskId,String docUrl,String docFilename,
                                                          ArrayList<ArrayList<Integer>> ranges) throws Exception {
        ArrayList<DocumentSplitRequest.Range> rangeList = new ArrayList<>();
        for (ArrayList<Integer> range : ranges) {
            rangeList.add(DocumentSplitRequest.Range.builder()
                    .start(range.get(0))
                    .end(range.get(1))
                    .build());
        }
        return splitFile(host,taskId,docUrl,docFilename,Constants.DocumentSplitType.AVERAGE,null,rangeList);
    }

    private static DocumentSplitResponse splitFile(String host,String taskId, String docUrl, String docFilename,
                                                   String type,
                                                   DocumentSplitRequest.Average average,
                                                   ArrayList<DocumentSplitRequest.Range> ranges) throws Exception {
        String url = "/api/cps/sync/v1/split";
        DocumentSplitRequest requestBody = DocumentSplitRequest.builder()
                .docUrl(docUrl)
                .docFilename(docFilename)
                .taskId(taskId)
                .type(type)
                .average(average)
                .ranges(ranges)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,DocumentSplitResponse.class);
    }

    public static SmartOfficalResponse smartDoc(String host,String taskId,String docUrl,String docFilename,
                                                String templateUrl,String templateFilename) throws Exception {
        String url = "/api/cps/sync/v1/smartofficial";
        SmartDocRequest requestBody = SmartDocRequest.builder()
                .taskId(taskId)
                .docUrl(docUrl)
                .docFilename(docFilename)
                .templateUrl(templateUrl)
                .templateFilename(templateFilename)
                .preInstallTemplate(Constants.SmartDocTemplate.BAO_GAO1)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,SmartOfficalResponse.class);
    }

    public static BookmarkPermissionsResponse setBookmarkPermissions(String host,String docUrl,
                                                                     String docFilename,
                                                                     Boolean allEditable,
                                                                     List<BookmarkPermissionsRequest.BookmarkPermission> bookmarkPermissionList) throws Exception {
        String url = "/api/cps/sync/v1/set/bookmarkpermissions";
        BookmarkPermissionsRequest requestBody = BookmarkPermissionsRequest.builder()
                .taskId(UUID.randomUUID().toString())
                .docUrl(docUrl)
                .docFilename(docFilename)
                .allEditable(allEditable)
                .bookmarkPermissionList(bookmarkPermissionList)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,BookmarkPermissionsResponse.class);
    }

    /**
     * 查询书签
     * @param host 中台入口地址
     * @param docUrl 文档地址
     * @param docFilename 文档名称
     */
    public static QueryBookmarkResponse queryBookmark(String host,String docUrl,
                                                                String docFilename,
                                                                String bookmarkType,
                                                      String bookmarkName) throws Exception {
        String url = "/api/cps/sync/v1/query/bookmark";
        QueryBookmarkRequest requestBody = QueryBookmarkRequest.builder()
                .taskId(UUID.randomUUID().toString())
                .docUrl(docUrl)
                .docFilename(docFilename)
                .bookmarkName(bookmarkName)
                .bookmarkType(bookmarkType)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,QueryBookmarkResponse.class);
    }

    /**
     * 查询只读、可写书签
     * @param host 中台入口地址
     * @param docUrl 文档地址
     * @param docFilename 文档名称
     * @param isEditable 是否只查询可编辑的书签
     */
    public static QueryBookmarkPermissionsResponse queryBookmarkPermissions(String host,String docUrl,
                                                                     String docFilename,
                                                                     Boolean isEditable) throws Exception {
        String url = "/api/cps/sync/v1/query/bookmarkpermissions";
        QueryBookmarkPermissionsRequest requestBody = QueryBookmarkPermissionsRequest.builder()
                .taskId(UUID.randomUUID().toString())
                .docUrl(docUrl)
                .docFilename(docFilename)
                .isEditable(isEditable)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,QueryBookmarkPermissionsResponse.class);
    }

    /**
     * 文档加解密
     * @param host 中台地址
     * @param docUrl 文档地址
     * @param docFilename 文档名称
     * @param originPassword 文档本身的密码
     * @param editPassword 编辑密码
     * @param openPassword 打开密码
     * @param removeEditPassword 是否移除编辑密码
     * @param removeOpenPassword 是否移除打开密码
     */
    public static DocumentPasswordResponse documentPasswordOperate(String host,String docUrl,
                                                                    String docFilename,
                                                                    String originPassword,
                                                                    String editPassword,
                                                                    String openPassword,
                                                                    Boolean removeEditPassword,
                                                                    Boolean removeOpenPassword) throws Exception {
        String url = "/api/cps/sync/v1/password";
        DocumentPasswordRequest requestBody = DocumentPasswordRequest.builder()
                .taskId(UUID.randomUUID().toString())
                .docUrl(docUrl)
                .docFilename(docFilename)
                .originOpenPassword(originPassword)
                .newEditPassword(editPassword)
                .newOpenPassword(openPassword)
                .removeEditPassword(removeEditPassword)
                .removeOpenPassword(removeOpenPassword)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,DocumentPasswordResponse.class);
    }

    public static ImageOperateResponse imageOperate(String host,
                                                    String imageUrl,
                                                   String imageFilename,
                                                   Float scale,
                                                    Integer width,
                                                    Integer height,
                                                    Float quality,
                                                    Integer rotate,
                                                    Boolean horizontalFlip,
                                                    Boolean verticalFlip,
                                                    ImageOperateRequest.TextWatermark textWatermark,
                                                    ImageOperateRequest.ImageWatermark imageWatermark
                                                    ) throws Exception {
        String url = "/api/cps/sync/v1/image/operate";
        ImageOperateRequest requestBody = ImageOperateRequest.builder()
                .taskId(UUID.randomUUID().toString())
                .imageUrl(imageUrl)
                .imageFilename(imageFilename)
                .scale(scale)
                .height(height)
                .width(width)
                .horizontalFlip(horizontalFlip)
                .verticalFlip(verticalFlip)
                .textWatermark(textWatermark)
                .imageWatermark(imageWatermark)
                .quality(quality)
                .rotate(rotate)
                .build();
        String content = JSON.toJSONString(requestBody);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.POST.toString(),content,CONTENT_TYPE);
        return HttpPostUtil.sendPostRequest(host+url,content,headers,ImageOperateResponse.class);
    }

    public static void operateDocumentResultDownload(String host,String downloadId,String routeKey,String savePath) throws Exception {
        String url = "/api/cps/v1/download/{download_id}";
        url = url.replace("{download_id}",downloadId);
        Map<String,String> headers = WPS4Util.getSignatureHeaders(url, HttpMethod.GET.toString(),null,CONTENT_TYPE);
        headers.put("Route-Key",routeKey);
        HttpPostUtil.sendGetDownloadRequest(host+url,headers,savePath);
    }
}
